<template>
  <div class="city">
    <van-index-bar :index-list="computedList" @select="hanglechange">
      <div v-for="data in citylist" :key="data.length">
        <van-index-anchor :index="data.type" />
        <van-cell
          v-for="item in data.list"
          :key="item.cityId"
          :title="item.name"
          @click="hangleitem(item)"
        />
      </div>
    </van-index-bar>
  </div>
</template>
<script>
import http from '@/util/httpAxios.js'
import { Toast } from 'vant'
export default {
  data() {
    return {
      citylist: []
    }
  },
  computed: {
    computedList() {
      return this.citylist.map((tiem) => {
        return tiem.type
      })
    }
  },
  mounted() {
    http({
      url: '/gateway?k=2929296',
      headers: {
        'X-Client-Info':
          '{"a":"3000","ch":"1002","v":"5.2.1","e":"16737777312402682014793729"}',
        'X-Host': 'mall.film-ticket.city.list'
      }
    }).then((res) => {
      //   console.log(res.data.data)
      this.citylist = this.renderCity(res.data.data.cities)
    })
  },
  methods: {
    renderCity(list) {
      //   console.log(list)
      const letterList = []
      const citylist = []
      for (let i = 65; i < 91; i++) {
        letterList.push(String.fromCharCode(i))
      }
      letterList.forEach((letter) => {
        const newList = list.filter(
          (item) => item.pinyin.substring(0, 1).toUpperCase() === letter
        )
        // console.log(newList)
        if (newList.length !== 0) {
          citylist.push({
            type: letter,
            list: newList
          })
        }
      })
      return citylist
    },
    hanglechange(data) {
      Toast({
        message: data,
        duration: 0
      })
    },
    hangleitem(item) {
      // this.$store.state.cityName = item.name
      this.$store.commit('changeCityName', item.name)
      this.$store.commit('changeCityId', item.cityId)
      this.$router.back()
    }
  }
}
</script>
<style lang="scss">
.van-toast--text {
  min-width: 25px;
}
</style>
